
package com.dog.basics.service.wishwash.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.model.common.DogConnectFlowing;
import com.dog.basics.bean.model.sys.SysUserInfo;
import com.dog.basics.bean.model.wishwash.DogHxBank;
import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.util.OrderCodeFactory;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.dao.sys.SysUserInfoMapper;
import com.dog.basics.dao.wishwash.DogHxBankMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxWithdrawalAddDto;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxWithdrawalEditDto;
import com.dog.basics.bean.dto.admin.wishwash.AdminDogHxWithdrawalFromDto;
import com.dog.basics.bean.vo.admin.wishwash.AdminDogHxWithdrawalVo;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import com.dog.basics.service.common.DogUserConnectService;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.model.wishwash.DogHxWithdrawal;
import com.dog.basics.dao.wishwash.DogHxWithdrawalMapper;
import com.dog.basics.service.wishwash.DogHxWithdrawalService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 提现记录
 *
 * @author cy code generator
 * @date 2021-07-09 17:40:27
 */
@Service
@AllArgsConstructor
public class DogHxWithdrawalServiceImpl extends ServiceImpl<DogHxWithdrawalMapper, DogHxWithdrawal> implements DogHxWithdrawalService {

    private SysUserInfoMapper userInfoMapper;
    private DogHxBankMapper hxBankMapper;
    private DogUserConnectService userConnectService;

    /**
     * @Description: 后台管理分页
     * @Param: status
     * @return: IPage
     * @author cy code generator
     * @date 2021-07-09 17:40:27
     */
    @Override
    public IPage<AdminDogHxWithdrawalVo> getAdminPageList(PageParam page, AdminDogHxWithdrawalFromDto obj) {
        // 声明用户标识如果为代理商或者场地则只查询自己的
        Long userId = null;
        if (SecurityUtils.hasRole(CommonConstants.ROLE_AGENT_CODE) || SecurityUtils.hasRole(CommonConstants.ROLE_FIELD_CODE)) {
            // 代理商
            userId = SecurityUtils.getSysUser().getUserId();
        }
        // 判断是否查用户名
        List<Long> userIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getUserName())) {
            // 查询用户信息
            List<Long> collect = userInfoMapper.selectList(Wrappers.<SysUserInfo>lambdaQuery().select(SysUserInfo::getUserId).eq(ObjectUtil.isNotNull(userId), SysUserInfo::getUserId, userId).like(SysUserInfo::getRealName, obj.getUserName())).stream().map(e -> e.getUserId()).collect(Collectors.toList());
            userIds = CollUtil.isNotEmpty(collect) ? collect : CollUtil.newArrayList(CommonConstants.DEFAULT_VAL_LONG);
        }
        // 后台管理 - 分页查询数据信息
        this.page(page, Wrappers.<DogHxWithdrawal>lambdaQuery()
                .eq(ObjectUtil.isNotNull(userId), DogHxWithdrawal::getUserId, userId)
                .in(CollUtil.isNotEmpty(userIds), DogHxWithdrawal::getUserId, userIds)
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), DogHxWithdrawal::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), DogHxWithdrawal::getCreateTime));
        // 格式化数据信息
        List<DogHxWithdrawal> records = page.getRecords();
        page.setRecords(records.stream().map(e -> {
            // 数据信息转换
            AdminDogHxWithdrawalVo objVo = BeanUtil.toBean(e, AdminDogHxWithdrawalVo.class);
            // 下面自定义格式化返回数据
            return objVo;
        }).collect(Collectors.toList()));
        // 数据返回
        return page;
    }

    /**
     * @Description: 用户提现
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAdminObj(AdminDogHxWithdrawalAddDto obj) {
        // 获取关联银行卡
        DogHxBank hxBank = hxBankMapper.selectById(obj.getBankId());
        // 判断银行卡是否存在
        Validator.validateNotNull(hxBank, "bank.no.error");
        // 判断银行卡是否属于本人
        Validator.validateEqual(hxBank.getId(), SecurityUtils.getSysUser().getUserId(), "bank.user.no.error");
        // 判断当前用户金额是否充足
        boolean greater = NumberUtil.isGreater(obj.getWithMoney(), BigDecimal.ZERO);
        Validator.validateTrue(greater, "user.flow.money.less");
        Boolean isUsetConnect = userConnectService.getIsUsetConnect(SecurityUtils.getSysUser().getUserId(), obj.getWithMoney());
        Validator.validateTrue(isUsetConnect, "user.connerct.money.Insufficient");
        // 数据信息转换添加提现记录
        DogHxWithdrawal objAdd = BeanUtil.toBean(obj, DogHxWithdrawal.class);
        // 数据信息补充
        objAdd.setUserId(SecurityUtils.getSysUser().getUserId());
        objAdd.setBankName(hxBank.getBankName());
        objAdd.setBankNo(hxBank.getBankNo());
        objAdd.setBankRealName(hxBank.getBankRealName());
        objAdd.setCreateTime(DateUtil.currentSeconds());
        objAdd.setCreateBy(SecurityUtils.getSysUser().getUserId());
        // 执行添加数据信息
        Validator.validateTrue(this.save(objAdd), "common.save");
        // 声明流水 - 补充流水信息
        DogConnectFlowing agentFlowing = new DogConnectFlowing();
        agentFlowing.setUserId(objAdd.getUserId());
        agentFlowing.setFlowSerialNo(OrderCodeFactory.getWaterCode(agentFlowing.getUserId()));
        agentFlowing.setFlowMoney(obj.getWithMoney().negate());
        agentFlowing.setFlowType(1);
        agentFlowing.setFromType(2);
        agentFlowing.setType(1);
        agentFlowing.setObjId(objAdd.getId());
        agentFlowing.setFlowExplain("Withdrawal");
        // 金额账户操作
        SpringContextUtils.getBean(DogUserConnectService.class).addUserConnect(agentFlowing.getUserId(), agentFlowing.getFlowMoney(), agentFlowing);
        return Boolean.TRUE;
    }

    /**
     * @Description: 后台管理修改
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-07-09 17:40:27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editAdminObj(AdminDogHxWithdrawalEditDto obj) {
        // 查询数据信息是否存在
        DogHxWithdrawal objInfo = this.getById(obj.getId());
        // 判断数据是否存
        Validator.validateNotNull(objInfo, "common.noData");
        // 判断状态必须为 0 、 1
        Validator.validateTrue(CollUtil.newArrayList(0,1).contains(objInfo.getWithState()), "withd.state.no.error");
        // 判断状态是否相符
        if (Validator.equal(obj.getWithState(), 1)){
            // 审核通过
            Validator.validateEqual(objInfo.getWithState(), 0, "withd.state.no.operation.audit");
        }else if (Validator.equal(obj.getWithState(), 2)){
            // 审核到账
            Validator.validateEqual(objInfo.getWithState(), 1, "withd.state.no.operation.audit");
        }
        // 数据信息转换
        DogHxWithdrawal editObj = BeanUtil.toBean(obj, DogHxWithdrawal.class);
        // 补充数据信息
        editObj.setUpdateTime(DateUtil.currentSeconds());
        editObj.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        // 执行修改信息
        Validator.validateTrue(this.updateById(editObj), "common.edit");
        return Boolean.TRUE;
    }

}
